const MusicPage = require("./MusicPage");
const {getSongIdFromUrl, sleep} = require("./Helper");
const path = require("path");
const Config = require("./Config");
const fs = require("fs");

class Album
{
    /**
     * @type {BrowserManager | null}
     */
    #browserManager = null;

    /**
     *
     * @type {User|null}
     */
    #user = null;
    constructor(browserManager)
    {
        this.#browserManager = browserManager
    }

    /**
     *
     * @param singerId
     * @return {Promise<Array[{url,title}]>}
     */
    async getFromWeb(singerId) {
        const singerUrl = 'https://music.163.com/#/artist/album?id=' + singerId + '&limit=1000&offset=0'
        console.log('获取专辑中...');
        const page = await this.#browserManager.openPage(singerUrl);
        const albums = await MusicPage.getAlbums(page);
        console.log('专辑数量:'+albums.length);
        await page.close();
        return albums
    }

    async saveToFile(singerId = 6452) {
        const albums = await this.getFromWeb(singerId);
        const data = {
            singerId : singerId,
            songMap : {},
        };
        for (const album of albums)
        {
            const page = await this.#browserManager.openPage(album.url);
            const songs = await MusicPage.getAlbumSongs(page);
            for (const song of songs)
            {
                if (data.songMap[song.name] === undefined)
                {
                    data.songMap[song.name] = [];
                }
                const songId = getSongIdFromUrl(song.url)
                data.songMap[song.name].push({
                    album : album.title,
                    songId : songId,
                });
                console.log(songId+'   '+song.name)

            } //end for songs
            await page.close();
            console.log(`${album.title}  ${songs.length}首歌`);
            await sleep(1000);
        }//end for albums
        // 生成文件路径

        if (!fs.existsSync(Config.singerSongDir)) {
            fs.mkdirSync(Config.singerSongDir, { recursive: true });
        }
        const filePath = path.join(Config.singerSongDir, `${singerId}.txt`);
        // 写入 JSON
        fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
        return true;
    }

    getDataBySingerId(singerId) {
        const filePath = path.join(Config.singerSongDir, `${singerId}.txt`);
        try {
            // 读取文本内容
            const content = fs.readFileSync(filePath, 'utf8');
            // 转换为 JSON 对象
            const data = JSON.parse(content);
            return data;
        } catch (err) {
            console.error('❌ 读取或解析文件失败:', err.message);
            return null;
        }
    }


}





module.exports = Album